package server;

import com.myservlet.HttpServlet;
import com.myservlet.Request;
import com.myservlet.Response;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Service service;

    public RequestProcessor(Socket socket, Service service) {
        this.socket = socket;
        this.service = service;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            HttpRequest request = new HttpRequest(inputStream);
            HttpResponse response = new HttpResponse(socket.getOutputStream());

            Object httpServlet = service.map(request, response);
            // 静态资源处理
            if(httpServlet == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                Method service = httpServlet.getClass().getMethod("service", Request.class, Response.class);
                service.invoke(httpServlet, request, response);
//                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
